package com.softtown.modules.dapai.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softtown.common.enums.IsDeleteEnum;
import com.softtown.common.service.impl.BaseServiceImpl;
import com.softtown.common.utils.ConvertUtils;
import com.softtown.modules.dapai.dao.CompCustomerDao;
import com.softtown.modules.dapai.dao.CompCustomerPotentialDao;
import com.softtown.modules.dapai.dto.*;
import com.softtown.modules.dapai.entity.*;
import com.softtown.modules.dapai.service.*;
import com.softtown.modules.dapai.vo.CompCustomerPotentialByContactVO;
import com.softtown.modules.dapai.vo.CompCustomerPotentialVO;
import com.softtown.modules.dapai.vo.CompCustomerVO;
import com.softtown.modules.dapai.vo.CustomerContactsVO;
import com.softtown.modules.oss.cloud.OSSFactory;
import com.softtown.modules.security.user.SecurityUser;
import com.softtown.modules.sys.dto.CompComDocAttAddDTO;
import com.softtown.modules.sys.entity.CompComDocAttEntity;
import com.softtown.modules.sys.service.CompComDocAttService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


@Service
public class CompCustomerPotentialServiceImpl extends
        BaseServiceImpl<CompCustomerPotentialDao, CompCustomerPotentialEntity> implements CompCustomerPotentialService {


    @Resource
    private CompCustomerPotentialContactsService compCustomerPotentialContactsService;

    @Resource
    private CompCustomerPotentialMacService compCustomerPotentialMacService;

    @Resource
    private CompCustomerPotentialVisitRecordsService compCustomerPotentialVisitRecordsService;

    @Resource
    private CompComDocAttService compComDocAttService;

    @Resource
    private CompCustomerService compCustomerService;

    @Resource
    private CompCustomerContactsService compCustomerContactsService;

    private static final String DOC_TYPE_VALUE = "comp_customer_potential";

    @Override
    public PageInfo<CompCustomerPotentialEntity> getPotentialPageList(CompCustomerPotentialDTO compCustomerPotentialDTO) {
        Integer pageSize = compCustomerPotentialDTO.getPageSize();
        Integer page = compCustomerPotentialDTO.getPage();
        if (pageSize > 0 && page > 0) {
            PageHelper.startPage(page, pageSize);
        }

        List<CompCustomerPotentialEntity>  compCustomerPotentialEntities =
                baseDao.getPotentialPageList(compCustomerPotentialDTO.getCompId(), compCustomerPotentialDTO.getParam());
        return new PageInfo<>(compCustomerPotentialEntities);
    }

    @Override
    public PageInfo<CompCustomerPotentialByContactVO> getPotentialContactList(CompCustomerPotentialByContactDTO compCustomerPotentialByContactDTO) {
        Integer pageSize = compCustomerPotentialByContactDTO.getPageSize();
        Integer page = compCustomerPotentialByContactDTO.getPage();
        if (pageSize > 0 && page > 0) {
            PageHelper.startPage(page, pageSize);
        }
        List<CompCustomerPotentialByContactVO>  compCustomerPotentialEntities =
                baseDao.getPotentialContactList(compCustomerPotentialByContactDTO.getCompId(), compCustomerPotentialByContactDTO.getParam());
        return new PageInfo<>(compCustomerPotentialEntities);
    }

    @Override
    public CompCustomerPotentialVO getPotentialById(Long compId, Long id) {
        CompCustomerPotentialVO compCustomerPotentialVO = new CompCustomerPotentialVO();
        compCustomerPotentialVO.setCompCustomerPotentialEntity(baseDao.getPotentialById(compId, id));
        compCustomerPotentialVO.setCompCustomerPotentialContactsEntities(compCustomerPotentialContactsService.
                list(new QueryWrapper<CompCustomerPotentialContactsEntity>().lambda().eq(CompCustomerPotentialContactsEntity::getCompId,compId)
                .eq(CompCustomerPotentialContactsEntity::getCustPotId,id)));
        compCustomerPotentialVO.setCompCustomerPotentialMacEntities(compCustomerPotentialMacService.
                list(new QueryWrapper<CompCustomerPotentialMacEntity>().lambda().eq(CompCustomerPotentialMacEntity::getCompId,compId)
                        .eq(CompCustomerPotentialMacEntity::getCustPotId,id)));
        compCustomerPotentialVO.setCompCustomerPotentialVisitRecordsEntities(compCustomerPotentialVisitRecordsService.
                list(new QueryWrapper<CompCustomerPotentialVisitRecordsEntity>().lambda().eq(CompCustomerPotentialVisitRecordsEntity::getCompId,compId)
                        .eq(CompCustomerPotentialVisitRecordsEntity::getCustPotId,id)));
        // 单据附件信息
        List<CompComDocAttEntity> compComDocAttEntities = compComDocAttService.getSysDocAttEntityByDocId(
                id, compId);
        if (compComDocAttEntities.size() > 0) {
            compCustomerPotentialVO.setDocAttList(compComDocAttEntities);
        } else {
            compComDocAttEntities = new ArrayList<>();
            compCustomerPotentialVO.setDocAttList(compComDocAttEntities);
        }
        return compCustomerPotentialVO;
    }


    @Override
    @Transactional
    public void addPotential(CustomerPotentialAddOrUpdateDTO customerPotentialAddOrUpdateDTO) {
        CompCustomerPotentialEntity compCustomerPotentialEntity = ConvertUtils
                .sourceToTarget(customerPotentialAddOrUpdateDTO.getCompCustomerPotentialDTO(), CompCustomerPotentialEntity.class);
        insert(compCustomerPotentialEntity);

        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialContactsDTOS().forEach(item ->{
            item.setCompId(compCustomerPotentialEntity.getCompId());
            item.setCustPotId(compCustomerPotentialEntity.getId());
        });
        compCustomerPotentialContactsService.insertBatch(ConvertUtils
                .sourceToTarget(customerPotentialAddOrUpdateDTO.getCompCustomerPotentialContactsDTOS(), CompCustomerPotentialContactsEntity.class));
        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialMacDTOList().forEach(item ->{
            item.setCustPotId(compCustomerPotentialEntity.getId());
            item.setCompId(compCustomerPotentialEntity.getCompId());
        });
        compCustomerPotentialMacService.insertBatch(ConvertUtils
                .sourceToTarget(customerPotentialAddOrUpdateDTO.getCompCustomerPotentialMacDTOList(), CompCustomerPotentialMacEntity.class));
        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialVisitRecordsDTOS().forEach(item ->{
            item.setCustPotId(compCustomerPotentialEntity.getId());
            item.setCompId(compCustomerPotentialEntity.getCompId());
        });
        compCustomerPotentialVisitRecordsService.insertBatch(ConvertUtils
                .sourceToTarget(customerPotentialAddOrUpdateDTO.getCompCustomerPotentialVisitRecordsDTOS(), CompCustomerPotentialVisitRecordsEntity.class));
        // 添加单据附件
        if (customerPotentialAddOrUpdateDTO.getCompComDocAttAddDTOList() != null) {
            if (customerPotentialAddOrUpdateDTO.getCompComDocAttAddDTOList().size() > 0) {
                insertCompComDocAttEntity(customerPotentialAddOrUpdateDTO.getCompComDocAttAddDTOList(), new Date(),
                        compCustomerPotentialEntity.getId(),
                        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialDTO().getCompId());
            }
        }
    }

    private void insertCompComDocAttEntity(List<CompComDocAttAddDTO> compComDocAttAddDTOS, Date nowDate, Long applId, Long compId) {
        // 添加单据附件
        HashSet set = new HashSet(compComDocAttAddDTOS);
        compComDocAttAddDTOS.clear();
        compComDocAttAddDTOS.addAll(set);
        for (int i = 0; i < compComDocAttAddDTOS.size(); i++) {
            CompComDocAttEntity compComDocAttEntity = new CompComDocAttEntity();
            compComDocAttEntity.setAttUrl(compComDocAttAddDTOS.get(i).getAttUrl());
            compComDocAttEntity.setCompId(compId);
            compComDocAttEntity.setAttName(compComDocAttAddDTOS.get(i).getAttName());
            compComDocAttEntity.setDocId(applId);
            compComDocAttEntity.setSctnLineNo(i + 1);
            compComDocAttEntity.setDocTypeValue(DOC_TYPE_VALUE);
            compComDocAttEntity.setCreateDate(nowDate);
            compComDocAttEntity.setCreator(SecurityUser.getUser().getId());
            compComDocAttEntity.setUpdateDate(nowDate);
            compComDocAttEntity.setUpdater(SecurityUser.getUser().getId());
            compComDocAttEntity.setUpdateTimestamp(Long.toString(System.currentTimeMillis()));
            compComDocAttService.insert(compComDocAttEntity);
        }
    }

    @Override
    @Transactional
    public void updatePotential(CustomerPotentialAddOrUpdateDTO customerPotentialAddOrUpdateDTO) {
        CompCustomerPotentialEntity compCustomerPotentialEntity = ConvertUtils
                .sourceToTarget(customerPotentialAddOrUpdateDTO.getCompCustomerPotentialDTO(), CompCustomerPotentialEntity.class);
        updateById(compCustomerPotentialEntity);

        List<CompCustomerPotentialContactsEntity> compCustomerPotentialContactsEntities =
                compCustomerPotentialContactsService.list(new QueryWrapper<CompCustomerPotentialContactsEntity>().lambda()
                .eq(CompCustomerPotentialContactsEntity::getCustPotId,compCustomerPotentialEntity.getId()));
        compCustomerPotentialContactsEntities.forEach(item ->{
            item.setCompId(compCustomerPotentialEntity.getCompId());
            item.setIsDeleted(IsDeleteEnum.DELETE.value());
        });
        compCustomerPotentialContactsService.updateBatchById(compCustomerPotentialContactsEntities);

        List<CompCustomerPotentialMacEntity> compCustomerPotentialMacEntities =
                compCustomerPotentialMacService.list(new QueryWrapper<CompCustomerPotentialMacEntity>().lambda()
                        .eq(CompCustomerPotentialMacEntity::getCustPotId,compCustomerPotentialEntity.getId()));
        compCustomerPotentialMacEntities.forEach(item ->{
            item.setCompId(compCustomerPotentialEntity.getCompId());
            item.setIsDeleted(IsDeleteEnum.DELETE.value());
        });
        compCustomerPotentialMacService.updateBatchById(compCustomerPotentialMacEntities);

        List<CompCustomerPotentialVisitRecordsEntity> compCustomerPotentialVisitRecordsEntities =
                compCustomerPotentialVisitRecordsService.list(new QueryWrapper<CompCustomerPotentialVisitRecordsEntity>().lambda()
                        .eq(CompCustomerPotentialVisitRecordsEntity::getCustPotId,compCustomerPotentialEntity.getId()));
        compCustomerPotentialVisitRecordsEntities.forEach(item ->{
            item.setCompId(compCustomerPotentialEntity.getCompId());
            item.setIsDeleted(IsDeleteEnum.DELETE.value());
        });
        compCustomerPotentialVisitRecordsService.updateBatchById(compCustomerPotentialVisitRecordsEntities);

        List<CompComDocAttEntity> compComDocAttEntities =
                compComDocAttService.getSysDocAttEntityByDocId(compCustomerPotentialEntity.getId(),
                        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialDTO().getCompId());
        if (compComDocAttEntities.size() > 0) {
            for (CompComDocAttEntity compComDocAttEntity : compComDocAttEntities) {
                Objects.requireNonNull(OSSFactory.build()).deleteFile(compComDocAttEntity.getAttUrl());
            }
            // 删除单据附件
            compComDocAttService.deleteByDocId(compCustomerPotentialEntity.getId(), customerPotentialAddOrUpdateDTO.getCompCustomerPotentialDTO().getCompId());
        }

        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialContactsDTOS().forEach(item ->{
            item.setCustPotId(compCustomerPotentialEntity.getId());
        });
        compCustomerPotentialContactsService.insertBatch(ConvertUtils
                .sourceToTarget(customerPotentialAddOrUpdateDTO.getCompCustomerPotentialContactsDTOS(), CompCustomerPotentialContactsEntity.class));
        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialMacDTOList().forEach(item ->{
            item.setCustPotId(compCustomerPotentialEntity.getId());
        });
        compCustomerPotentialMacService.insertBatch(ConvertUtils
                .sourceToTarget(customerPotentialAddOrUpdateDTO.getCompCustomerPotentialMacDTOList(), CompCustomerPotentialMacEntity.class));
        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialVisitRecordsDTOS().forEach(item ->{
            item.setCustPotId(compCustomerPotentialEntity.getId());
        });
        compCustomerPotentialVisitRecordsService.insertBatch(ConvertUtils
                .sourceToTarget(customerPotentialAddOrUpdateDTO.getCompCustomerPotentialVisitRecordsDTOS(), CompCustomerPotentialVisitRecordsEntity.class));
        // 添加单据附件
        if (customerPotentialAddOrUpdateDTO.getCompComDocAttAddDTOList() != null) {
            if (customerPotentialAddOrUpdateDTO.getCompComDocAttAddDTOList().size() > 0) {
                insertCompComDocAttEntity(customerPotentialAddOrUpdateDTO.getCompComDocAttAddDTOList(), new Date(),
                        compCustomerPotentialEntity.getId(),
                        customerPotentialAddOrUpdateDTO.getCompCustomerPotentialDTO().getCompId());
            }
        }
    }


    @Override
    @Transactional
    public void deletePotential(Long compId, Long id) {
        // 先删明细
        List<CompCustomerPotentialContactsEntity> compCustomerPotentialContactsEntities =
                compCustomerPotentialContactsService.list(new QueryWrapper<CompCustomerPotentialContactsEntity>().lambda()
                .eq(CompCustomerPotentialContactsEntity::getCustPotId,id));
        compCustomerPotentialContactsEntities.forEach(item ->{
            item.setIsDeleted(IsDeleteEnum.DELETE.value());
        });
        compCustomerPotentialContactsService.updateBatchById(compCustomerPotentialContactsEntities);

        List<CompCustomerPotentialMacEntity> compCustomerMacEntities = compCustomerPotentialMacService.list(new QueryWrapper<CompCustomerPotentialMacEntity>().lambda()
                .eq(CompCustomerPotentialMacEntity::getCustPotId,id));
        compCustomerMacEntities.forEach(item ->{
            item.setIsDeleted(IsDeleteEnum.DELETE.value());
        });
        compCustomerPotentialMacService.updateBatchById(compCustomerMacEntities);

        List<CompCustomerPotentialVisitRecordsEntity> compCustomerReceiveEntities =
                compCustomerPotentialVisitRecordsService.list(new QueryWrapper<CompCustomerPotentialVisitRecordsEntity>().lambda()
                .eq(CompCustomerPotentialVisitRecordsEntity::getCustPotId,id));
        compCustomerReceiveEntities.forEach(item ->{
            item.setIsDeleted(IsDeleteEnum.DELETE.value());
        });
        compCustomerPotentialVisitRecordsService.updateBatchById(compCustomerReceiveEntities);

        List<CompComDocAttEntity> compComDocAttEntities =
                compComDocAttService.getSysDocAttEntityByDocId(id,
                        compId);
        if (compComDocAttEntities.size() > 0) {
            for (CompComDocAttEntity compComDocAttEntity : compComDocAttEntities) {
                Objects.requireNonNull(OSSFactory.build()).deleteFile(compComDocAttEntity.getAttUrl());
            }
            // 删除单据附件
            compComDocAttService.deleteByDocId(id,compId);
        }

        // 删除主表
        CompCustomerPotentialEntity compCustomerPotentialEntity = baseDao.selectOne(new QueryWrapper<CompCustomerPotentialEntity>().lambda().eq(CompCustomerPotentialEntity ::getId,id)
        .eq(CompCustomerPotentialEntity::getCompId,compId));
        compCustomerPotentialEntity.setIsDeleted(IsDeleteEnum.DELETE.value());
        baseDao.updateById(compCustomerPotentialEntity);
    }


    @Override
    @Transactional
    public void transPotential(Long compId, Long id) {
        CompCustomerPotentialEntity compCustomerPotentialEntity = baseDao.selectOne(new QueryWrapper<CompCustomerPotentialEntity>().lambda().eq(CompCustomerPotentialEntity ::getId,id)
                .eq(CompCustomerPotentialEntity::getCompId,compId));

        CompCustomerEntity compCustomerEntity = new CompCustomerEntity();
        compCustomerEntity.setIsDeleted(IsDeleteEnum.NORMAL.value());
        compCustomerEntity.setProCityId(compCustomerPotentialEntity.getProCityId());
        compCustomerEntity.setAddress(compCustomerPotentialEntity.getAddress());
        compCustomerEntity.setName(compCustomerPotentialEntity.getName());
        compCustomerEntity.setProduce(compCustomerPotentialEntity.getProduce());
        compCustomerEntity.setAreaCityId(compCustomerPotentialEntity.getAreaCityId());
        compCustomerEntity.setCityId(compCustomerPotentialEntity.getCityId());
        compCustomerEntity.setCompId(compId);
        compCustomerEntity.setEmplId(compCustomerPotentialEntity.getEmplId());
        compCustomerService.insert(compCustomerEntity);

        List<CompComDocAttEntity> compComDocAttEntities =
                compComDocAttService.getSysDocAttEntityByDocId(id,
                        compId);
        if (compComDocAttEntities.size() >0){
            for (CompComDocAttEntity compComDocAttEntity : compComDocAttEntities) {
                compComDocAttEntity.setDocId(compCustomerEntity.getId());
            }
            compComDocAttService.updateBatchById(compComDocAttEntities);
        }
        List<CompCustomerPotentialContactsEntity> compCustomerPotentialContactsEntities =
                compCustomerPotentialContactsService.list(new QueryWrapper<CompCustomerPotentialContactsEntity>().lambda()
                        .eq(CompCustomerPotentialContactsEntity::getCustPotId,id));
        List<CompCustomerContactsEntity> compCustomerContactsEntities = new ArrayList<>();
        for(int i =0; i<compCustomerPotentialContactsEntities.size();i++){
            CompCustomerContactsEntity compCustomerContactsEntity = new CompCustomerContactsEntity();
            if(i== 0){
                compCustomerContactsEntity.setIsDefault(IsDeleteEnum.DELETE.value());
            }else {
                compCustomerContactsEntity.setIsDefault(IsDeleteEnum.NORMAL.value());
            }
            compCustomerContactsEntity.setCustId(compCustomerEntity.getId());
            compCustomerContactsEntity.setCompId(compId);
            compCustomerContactsEntity.setContact(compCustomerPotentialContactsEntities.get(i).getContact());
            compCustomerContactsEntity.setTelephone(compCustomerPotentialContactsEntities.get(i).getTelephone());
            compCustomerContactsEntity.setMobile(compCustomerPotentialContactsEntities.get(i).getMobile());
            compCustomerContactsEntity.setEmail(compCustomerPotentialContactsEntities.get(i).getEmail());
            compCustomerContactsEntity.setWebsite(compCustomerPotentialContactsEntities.get(i).getWebsite());
            compCustomerContactsEntity.setRemark(compCustomerPotentialContactsEntities.get(i).getRemark());
            compCustomerContactsEntity.setIsDeleted(IsDeleteEnum.NORMAL.value());
            compCustomerContactsEntities.add(compCustomerContactsEntity);
        }
        compCustomerContactsService.insertBatch(compCustomerContactsEntities);

        compCustomerPotentialEntity.setIsDeleted(IsDeleteEnum.DELETE.value());
        baseDao.updateById(compCustomerPotentialEntity);

    }
}
